<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\WebPage;
use StudyBuddy\MongoDoc;

class Requestactivation extends WebPage
{
	const EMAIL_BODY = 'Welcome to %1$s!

IMPORTANT: You Must use the link below to activate your account
%2$s

	';

	const SUBJECT = '%s account activation';

	const SUCCESS = 'Activation instructions have just been emailed to you to %s';


	protected $membersOnly = true;
	
	protected $layoutID = 1;

	protected $oEmail;

	protected $email;

	protected function main(){
		$this->aPageVars['title'] = 'Request email confirmation';

		$this->getEmailObject()
		->makeActivationCode()
		->sendActivationEmail();

		$this->aPageVars['body'] = '<div id="tools">'.sprintf(self::SUCCESS, $this->email).'</div>';
	}


	/**
	 *
	 * Create object representing email address
	 * of current Viewer
	 *
	 * @throws \StudyBuddy\NoemailException if unable to find email address
	 * of current Viewer
	 *
	 * @return object $this
	 */
	protected function getEmailObject(){
		$this->email = strtolower($this->oRegistry->Viewer->email);
		if(empty($this->email)){
			throw new \StudyBuddy\NoemailException('You have not selected any email address for your account yet');
		}

		$this->oEmail = MongoDoc::factory($this->oRegistry, 'EMAILS')->byEmail($this->email);
		if('' == $this->oEmail['email']){
			throw new \StudyBuddy\NoemailException('You have not selected any email address for your account yet');
		}

		return $this;
	}



	protected function makeActivationCode(){

		if((!empty($this->oEmail['i_vts'])) && $this->oEmail['i_vts'] > 0){
			throw new \StudyBuddy\Exception('This account has already been activated');
		}

		$code = $this->oEmail['code'];

		if(empty($code)){
			$this->oEmail['code'] = substr(hash('md5', uniqid(mt_rand())), 0, 12);
		}

		$this->oEmail['i_code_ts'] = time();

		$this->oEmail['i_vts'] = null;
		$this->oEmail->save();

		return $this;
	}


	/**
	 * Email activation link to user
	 *
	 * @throws \StudyBuddy\Exception if unable to email
	 *
	 * @return object $this
	 */
	protected function sendActivationEmail()
	{
		$tpl = $this->oRegistry->Ini->SITE_URL.'/aa/%d/%s';
		$link = sprintf($tpl, $this->oEmail['_id'], $this->oEmail['code']);
		d('$link: '.$link);
		
		$siteName = $this->oRegistry->Ini->SITE_NAME;
		$body = vsprintf(self::EMAIL_BODY, array($siteName, $link));
		$subject = sprintf(self::SUBJECT, $siteName);
		\StudyBuddy\Mailer::factory($this->oRegistry)->mail($this->email, $subject, $body);

		return $this;
	}

}
